﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace ConApp3._1
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //var services = new ServiceCollection();
            //services.AddHttpClient("yunwei", client =>
            //{
            //    client.BaseAddress = new Uri("https://yunwei.beijing.gwhome:34443/");
            //    client.DefaultRequestVersion = new Version(2, 0);
            //}).ConfigurePrimaryHttpMessageHandler(() =>
            //{
            //    var currentDir = Directory.GetCurrentDirectory();
            //    Console.WriteLine("当前工作目录: " + currentDir);

            //    var certPath = Path.Combine(currentDir, "certs", "李克善_new.p12");
            //    Console.WriteLine("加载证书路径: " + certPath);

            //    if (!File.Exists(certPath))
            //    {
            //        throw new FileNotFoundException("证书文件不存在", certPath);
            //    }
            //    var certs = new X509Certificate2(certPath, "wXsjm1VN", X509KeyStorageFlags.PersistKeySet);
            //    //var certs = LoadCertificateFromStore("李克善");
            //    //var certs = new X509Certificate2(certPath, "wXsjm1VN");

            //    Console.WriteLine("证书主题: " + certs.Subject);
            //    Console.WriteLine("是否包含私钥: " + certs.HasPrivateKey);

            //    //var handler = new HttpClientHandler
            //    //{
            //    //    ClientCertificates = { certs },
            //    //    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // 仅测试
            //    //    ClientCertificateOptions = ClientCertificateOption.Manual,
            //    //    SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
            //    //    UseCookies = true,
            //    //    //AllowAutoRedirect = false,
            //    //};
            //    //var cert = LoadCertificateFromStore("李克善");
            //    //var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
            //    var handler = new SocketsHttpHandler
            //    {
            //        UseCookies = true,
            //        AllowAutoRedirect = true,
            //        // 设置客户端证书
            //        SslOptions = new SslClientAuthenticationOptions
            //        {
            //            TargetHost = "yunwei.beijing.gwhome",
            //            ClientCertificates = new X509CertificateCollection { certs },
            //            //ClientCertificates = { certs },
            //            // 设置服务器证书验证回调（仅测试用）
            //            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
            //            // 设置 SSL/TLS 协议版本
            //            EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
            //            // 设置客户端认证选项
            //            CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
            //        },
            //    };

            //    return handler;

            //});


            //var provider = services.BuildServiceProvider();
            await ProcessSomething();

        }

        private static HttpMessageHandler CreateMessageHandler(bool allowAutoRedirect)
        {
            var currentDir = Directory.GetCurrentDirectory();
            Console.WriteLine("当前工作目录: " + currentDir);

            var certPath = Path.Combine(currentDir, "certs", "李克善.p12");

            Console.WriteLine("加载证书路径: " + certPath);

            if (!File.Exists(certPath))
            {
                throw new FileNotFoundException("证书文件不存在", certPath);
            }
            var certs = new X509Certificate2(certPath, "wXsjm1VN", X509KeyStorageFlags.PersistKeySet);
            //var certs = LoadCertificateFromStore("李克善");
            //var certs = new X509Certificate2(certPath, "wXsjm1VN");

            Console.WriteLine("证书主题: " + certs.Subject);
            Console.WriteLine("是否包含私钥: " + certs.HasPrivateKey);
            var handler = new HttpClientHandler
            {
                ClientCertificates = { certs },
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // 仅测试
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
                UseCookies = true,
                AllowAutoRedirect = allowAutoRedirect,
            };

            return handler;
        }

        private static async Task ProcessSomething()
        {
            string loginUrl = $"/login/";
            string authenticateUrl = $"/authenticate/";

            string userName = "likeshan";
            string password = "Sfqd@20220428";
            string baseUrl = "https://yunwei.beijing.gwhome:34443";
            try
            {

                var authRequest = new HttpRequestMessage(HttpMethod.Post, authenticateUrl);
                authRequest.Headers.Add("Referer", $"{baseUrl}{loginUrl}");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                //authRequest.Headers.Add("Host", "yunwei.beijing.gwhome:34443");
                //authRequest.Headers.Add("Origin", "https:yunwei.beijing.gwhome:34443");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");


                // 创建 HttpClient 并发送请求
                using (var httpClient = new HttpClient(CreateMessageHandler(false)))
                {
                    httpClient.DefaultRequestVersion = new Version(2, 0);
                    httpClient.BaseAddress = new Uri(baseUrl);

                    // 发送 GET 请求
                    var response = await httpClient.GetAsync(loginUrl);
                    Console.WriteLine(response.Version);

                    // var html = await response.Content.ReadAsStringAsync();
                    // Console.WriteLine(html);

                    // request.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Response Status: Success");

                        // 获取响应头中的 Set-Cookie 字段
                        if (response.Headers.TryGetValues("Set-Cookie", out var cookieValues))
                        {
                            foreach (var cookie in cookieValues)
                            {
                                Console.WriteLine("Received Set-Cookie: " + cookie);
                                authRequest.Headers.Add("Cookie", cookie);
                            }
                        }

                        // 3. 获取 csrftoken（从 Cookie 中）
                        // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                        var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                        if (csrfCookie != null)
                        {
                            var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                            if (csrfValue != null)
                            {
                                var token = csrfValue.Substring("csrftoken=".Length);
                                authRequest.Headers.Add("X-CSRFToken", token);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Error: {response.StatusCode}");
                    }
                }


                // 为 C# 8.0 兼容，改为：
                var collection = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("username", userName),
                    new KeyValuePair<string, string>("password", password)
                };
                var content = new FormUrlEncodedContent(collection);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                authRequest.Content = content;
                
                using (var httpClient = new HttpClient(CreateMessageHandler(false)))
                {
                    httpClient.BaseAddress = new Uri(baseUrl);
                    var postResponse = await httpClient.SendAsync(authRequest);
                    Console.WriteLine(postResponse.Version);
                    // 6. 处理响应
                    if (postResponse.IsSuccessStatusCode)
                    {
                        var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                        var jsonStr = Encoding.UTF8.GetString(responseBody);
                        Console.WriteLine("请求成功！");
                        Console.WriteLine($"状态码: {postResponse.StatusCode}");
                        Console.WriteLine($"响应内容: {jsonStr}");
                    }
                    else
                    {
                        Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                        Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                // 专门捕获 HTTP 层异常，可能包含内部异常
                Console.WriteLine($"HTTP 请求异常: {httpEx.Message}");
                if (httpEx.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {httpEx.InnerException.Message}");
                    // 这里可能会看到 "The credentials supplied to the package were not recognized"
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}，{ex.InnerException?.Message}，{ex.StackTrace}");
                if (ex is CryptographicException cryptoEx)
                {
                    Console.WriteLine($"加密错误详情: {cryptoEx.Message}");
                }
            }

        }
        private static X509Certificate2 LoadCertificateFromStore(string subjectOrFriendlyName)
        {
            // 尝试在当前用户的“个人”存储区中查找
            using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);
                var collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectOrFriendlyName, false);
                if (collection.Count > 0)
                {
                    return collection[0]; // 返回第一个匹配的证书
                }
            }

            // 尝试在本地计算机的“个人”存储区中查找
            using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadOnly);
                var collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectOrFriendlyName, false);
                if (collection.Count > 0)
                {
                    return collection[0];
                }
            }

            return null;
        }

    }
}
